from rest_framework import serializers

from goods.models import SKU


# 购物车视图
class CartSerialzers(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=1)
    count = serializers.IntegerField(min_value=1)
    selected = serializers.BooleanField(default=True)

    def validate(self, attrs):
        # 判断sku——id是否存在
        try:
            sku = SKU.objects.get(id=attrs['sku_id'])

        except:
            raise serializers.ValidationError('商品不存在')
        # 判断库存
        if attrs['count'] > sku.stock:
            raise serializers.ValidationError('商品库存不足')

        return attrs


# 获取购物车的数据
class CartGetSerializers(serializers.ModelSerializer):
    count = serializers.IntegerField(read_only=True)
    selected = serializers.BooleanField(read_only=True)

    class Meta:
        model = SKU
        fields = '__all__'


# 购物车的删除序列化器
class CartDeleteSerialzers(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=1)

    def validate(self, attrs):
        # 判断sku——id是否存在
        try:
            sku = SKU.objects.get(id=attrs['sku_id'])

        except:
            raise serializers.ValidationError('商品不存在')

        return attrs


# 购物车的全选序列化器
class CartSelectionSerialzers(serializers.Serializer):
    selected = serializers.BooleanField()
